import 'rxjs/add/operator/switchMap';

import { OnInit, Input, Component } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import {
  trigger,
  state,
  style,
  animate,
  transition
} from '@angular/animations';

import { Hero } from '../shared/hero.model';
import { HeroService } from '../shared/hero.service';

@Component({
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css'],
  animations: [
    trigger('heroState', [
      state('inactive', style({
        backgroundColor: '#eee',
        transform: 'scale(1)'
      })),
      state('active', style({
        backgroundColor: '#cfd8dc',
        transform: 'scale(1.1)'
      })),
      transition('inactive => active', animate('100ms ease-in')),
      transition('active => inactive', animate('100ms ease-out'))
    ])
  ]
})
export class HeroListComponent implements OnInit {
  // heroes: Observable<Hero[]>;
  private selectedId: number;
  title = 'Tour of Heroes!';
  @Input() heroes: Hero[];
  // 添加点击选中英雄
  selectedHero: Hero;
  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private router: Router

  ) {
  }

  /**
   *  初始化
   */
  // ngOnInit() {
  //   this.heroes = this.route.params
  //     .switchMap((params: Params) => {
  //       this.selectedId = +params['id'];
  //       // return this.getHeroes();
  //     });
  // }

  ngOnInit(): void {
    // this.route.params
    //   .switchMap((params: Params) => {
    //     this.selectedId = +params['id'];
    //     return this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    //   });

    this.getHeroes();
  }
  /**
   * 选择英雄
   */
  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  };

  isSelected(hero: Hero) { return hero.id === this.selectedId; }


  /**
   * 英雄列表
   */
  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  };
  /**
   * 跳转详情
   */
  gotoDetail(): void {
    this.router.navigate(['/heroes', this.selectedHero.id]);
  }

  /**
   * 添加英雄
   */
  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.create(name)
      .then(hero => {
        this.heroes.push(hero);
        this.selectedHero = null;
      });
  }

  /**
   * 删除英雄
   */
  delete(hero: Hero): void {
    this.heroService
      .delete(hero.id)
      .then(() => {
        this.heroes = this.heroes.filter(h => h !== hero);
        if (this.selectedHero === hero) { this.selectedHero = null; }
      });
  }
}
